package mobweb.booktrack;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.support.v4.app.NavUtils;

public class BookSearchList extends Activity {
    private LinearLayout mainLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_book_search_list);
	// Show the Up button in the action bar.
	//getActionBar().setDisplayHomeAsUpEnabled(true);
	
	Intent i = getIntent();
	Bundle b = i.getExtras();
	if (b!=null) {
	   try {
	    JSONObject json = new JSONObject(b.getString("json"));
	    Book[] bList = jsonToBookList(json);
	    loadBooks(bList);
	} catch (JSONException e) {
	    e.printStackTrace();
	} catch (Exception e) {
	    
	}
	} else {
	    
	}
	
    }

    private Book[] jsonToBookList(JSONObject jso) {
	Book[] bList = null;
	try {
	    int total = jso.getInt("totalItems");
	    if (total > 0) {
        	JSONArray items = jso.getJSONArray("items");
        	int realLength = items.length();
        	bList = new Book[realLength];
        	for (int i = 0; i<realLength; i++) {
        	    Book book = new Book();
        	    book.setFlag(Book.UNSPECIFIED);
        	    book.setId(-1);
        	    JSONObject item = items.getJSONObject(i);
        	    if (item.has("volumeInfo")) {
        		JSONObject volumeInfo = item.getJSONObject("volumeInfo");
        		
        		if(volumeInfo.has("title"))
        		{
        		    book.setBookName(volumeInfo.getString("title"));
        		}
                		
                	if(volumeInfo.has("authors"))
                	{
                	    book.setAuthor(convertArrayToString(volumeInfo.getJSONArray("authors")));
                	}
                		
                	if(volumeInfo.has("categories"))
                	{
                	    book.setCategory(convertArrayToString(volumeInfo.getJSONArray("categories")));
                	}
                		
                	if(volumeInfo.has("description"))
                	{
                	    book.setDescription(volumeInfo.getString("description"));
                	}
                		
                	if(volumeInfo.has("industryIdentifiers"))
                	{ 
                	    JSONArray isbnArray = volumeInfo.getJSONArray("industryIdentifiers");
        					
                	    for (int isbnCount=0;isbnCount<isbnArray.length();isbnCount++) {
                		JSONObject isbn=(JSONObject)isbnArray.get(isbnCount);
        				      
                		if(isbn.getString(("type")).equals("ISBN_13")) {
                		    book.setISBN(isbn.getString("identifier"));
                		}
                	    }
                	}
                    }
        	}
	    }
	} catch (JSONException e){
	    e.printStackTrace();
	}
	return bList;
    }
    
    private void addBook(final Book b) {
	mainLayout = (LinearLayout) findViewById(R.id.MainLinearLayout);
	// TODO Add book b to UI
	LinearLayout childLayout = new LinearLayout(getBaseContext());
	LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
	childLayout.setLayoutParams(lp);
	childLayout.setOrientation(LinearLayout.HORIZONTAL);
	childLayout.setGravity(Gravity.LEFT);
	childLayout.setClickable(true);

	ImageView bookImage = new ImageView(getBaseContext());
	// TODO query google books api here for an image
	childLayout.addView(bookImage);

	LinearLayout child2 = new LinearLayout(getBaseContext());
	child2.setOrientation(LinearLayout.VERTICAL);
	
	Button but = new Button(getBaseContext());
	but.setText("Details");
	but.setOnClickListener(new OnClickListener() {

	    @Override
	    public void onClick(View v) {
		Intent i = new Intent(getApplicationContext(), BookActivity.class);
		i.putExtra("book", b);
		startActivity(i);
	    }
	    
	});

	TextView bookTitle = new TextView(getBaseContext());
	bookTitle.setText(b.getBookName());
	bookTitle.setTextSize(20);
	bookTitle.setTextColor(Color.BLACK);
	child2.addView(bookTitle);
	
	TextView bookAuthor = new TextView(getBaseContext());
	bookAuthor.setText(b.getAuthor());
	bookAuthor.setTextSize(16);
	bookAuthor.setTextColor(Color.BLACK);
	child2.addView(bookAuthor);

	TextView bookDesc = new TextView(getBaseContext());
	bookDesc.setText(b.getDescription());
	child2.addView(bookDesc);
	
	childLayout.addView(child2);
	childLayout.addView(but);
	
	mainLayout.addView(childLayout);
    }
    
    private void loadBooks(final Book[] b) {
	// TODO load the books into the UI
	for (int i = 0; i<b.length; i++) {
	    addBook(b[i]);
	}
	if (b.length == 0) {
		mainLayout = (LinearLayout) findViewById(R.id.MainLinearLayout);
		TextView noBooks = new TextView(getBaseContext());
		noBooks.setText("You have no books in the list");
		noBooks.setGravity(Gravity.CENTER_HORIZONTAL);
		noBooks.setTextSize(30);
		noBooks.setTextColor(Color.BLACK);
		mainLayout.addView(noBooks);
	}
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
	// Inflate the menu; this adds items to the action bar if it is present.
	getMenuInflater().inflate(R.menu.activity_book_search_list, menu);
	return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
	switch (item.getItemId()) {
	case android.R.id.home:
	    // This ID represents the Home or Up button. In the case of this
	    // activity, the Up button is shown. Use NavUtils to allow users
	    // to navigate up one level in the application structure. For
	    // more details, see the Navigation pattern on Android Design:
	    //
	    // http://developer.android.com/design/patterns/navigation.html#up-vs-back
	    //
	    NavUtils.navigateUpFromSameTask(this);
	    return true;
	}
	return super.onOptionsItemSelected(item);
    }
    
    private static String convertArrayToString(JSONArray arr) throws JSONException {
	String result = "";
	result = result + arr.getString(0);
	
	for (int i = 1; i < arr.length(); i++){
	    result = result + ", " + arr.getString(i);
	}
	
	return result;
    }

}
